package com.github.aloxc.plugin.restplus.component;

import com.github.aloxc.plugin.restplus.component.listener.VTreeMouseListener;
import com.github.aloxc.plugin.restplus.component.listener.VTreeShow;
import com.github.aloxc.plugin.restplus.exception.JsonException;
import com.github.aloxc.plugin.restplus.utils.JsonUtils;
import com.intellij.openapi.editor.colors.FontPreferences;
import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBPanel;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Base64;

import static com.github.aloxc.plugin.restplus.common.Consts.LINE_NUMBER_BACKGROUND_COLOR;
import static javax.swing.ScrollPaneConstants.*;

/**
 * @author leero
 */
public class JWTForm extends JBPanel {
    private JPanel jsonToolPanel;
    private JScrollPane leftScroll;
    private JPanel rootPanel;
    private JScrollPane rightScroll;

    private Project project;
    private TextPane rightTextPane;
    private TextPane leftTextPane;
    private int JsonToolHeight = 600;
    private VTree responseTree;

    private Font FONT = null;

    public JWTForm(Project project) {
        super();
        this.project = project;
        initComponent();
    }

    private static ThreadLocal<SimpleDateFormat> SIMPLE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        }
    };


    public void initComponent() {
        initUi();
        SimpleAttributeSet keyAttr = new SimpleAttributeSet();
        StyleConstants.setFontSize(keyAttr, 14);
//        initTreeData();
        initActions();
        FONT = new Font("Monospaced", Font.PLAIN, 14);

    }

    private void initActions() {
        bindJsonToolTreeListener();

    }


    public Project getProject() {
        return project;
    }

    public void setProject(Project Project) {
        this.project = Project;
    }


    private void bindJsonToolTreeListener() {
        leftTextPane.getDocument().addDocumentListener(new JwtTextListener());
//        JsonToolTree.addTreeSelectionListener(new JsonToolTreeSelectionListener(project, JsonToolDetailTextPane));
    }

    @Override
    protected void printComponent(Graphics g) {
        super.printComponent(g);
    }

    private void initUi() {
        GridLayoutManager JsonToolLayout = new GridLayoutManager(1, 2);
        JsonToolLayout.setHGap(1);
        JsonToolLayout.setVGap(1);
        JsonToolLayout.setMargin(new Insets(20, 20, 20, 20));
        jsonToolPanel = new JBPanel<>();
        jsonToolPanel.setLayout(JsonToolLayout);
        jsonToolPanel.setMaximumSize(new Dimension(-1, JsonToolHeight));
        jsonToolPanel.setMinimumSize(new Dimension(-1, JsonToolHeight));
        jsonToolPanel.setPreferredSize(new Dimension(-1, JsonToolHeight));
        this.setBorder(BorderFactory.createEmptyBorder());
        this.setLayout(new GridLayoutManager(1, 1));


        initLeft();
        initRight();
        initJsonToolPanel();
    }

    private void initJsonToolPanel() {

        this.add(jsonToolPanel,
                new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTHWEST, GridConstraints.FILL_BOTH,
                        GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
                        GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
                        new Dimension(-1, JsonToolHeight), new Dimension(-1, JsonToolHeight), new Dimension(-1, JsonToolHeight)));
    }

    private void initRight() {

        ScrollPaneLayout jsonToolDetailScrollLayout = new ScrollPaneLayout();
        jsonToolDetailScrollLayout.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jsonToolDetailScrollLayout.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED);
        rightScroll.setLayout(jsonToolDetailScrollLayout);
        rightTextPane = new TextPane(LINE_NUMBER_BACKGROUND_COLOR, project);


        responseTree = new VTree(LINE_NUMBER_BACKGROUND_COLOR);
        responseTree.setShowLineNumber(true);
        responseTree.setRowHeight(22);
        SimpleAttributeSet keyAttr = new SimpleAttributeSet();
        StyleConstants.setFontSize(keyAttr, 14);
        Font font = new Font(FontPreferences.DEFAULT_FONT_NAME, Font.PLAIN, 14);
        responseTree.setFont(font);
        responseTree.setRootVisible(false);
        responseTree.setShowsRootHandles(false);
        DefaultTreeModel model = (DefaultTreeModel) responseTree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        model.reload(root);



//        responseTree.setText("afdsfdsfads");

        rightScroll.getViewport().add(responseTree,
                new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_SOUTHEAST, GridConstraints.FILL_BOTH,
                        GridConstraints.SIZEPOLICY_FIXED,
                        GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
                        new Dimension(-1, -1), new Dimension(-1, -1), new Dimension(-1, -1)));
        jsonToolPanel.add(rightScroll,
                new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_SOUTHEAST, GridConstraints.FILL_BOTH,
                        GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
                        GridConstraints.FILL_NONE,
                        new Dimension(-1, -1), new Dimension(-1, -1), new Dimension(-1, -1)));
    }

    private void initLeft() {
        int JsonToolWidth = 430;
        ScrollPaneLayout JsonToolListScrollLayout = new ScrollPaneLayout();
        JsonToolListScrollLayout.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
        JsonToolListScrollLayout.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED);
        leftScroll.setLayout(JsonToolListScrollLayout);
        leftScroll.setPreferredSize(new Dimension(JsonToolWidth, JsonToolHeight));

        leftTextPane = new TextPane(LINE_NUMBER_BACKGROUND_COLOR, project) {
            @Override
            public boolean getScrollableTracksViewportWidth() {
                return false;
            }
        };
        leftTextPane.setShowLineNumber(true);
//        leftTextPane.setText("xxxxxxx");
        leftTextPane.setFont(FONT);
        leftTextPane.setJavascript(false);
//        leftTextPane.format();

        leftScroll.getViewport().add(leftTextPane,
                new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_SOUTHEAST, GridConstraints.FILL_BOTH,
                        GridConstraints.SIZEPOLICY_FIXED,
                        GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
                        new Dimension(JsonToolWidth, -1), new Dimension(JsonToolWidth, -1), new Dimension(JsonToolWidth, -1)));
        jsonToolPanel.add(leftScroll,
                new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_SOUTHEAST, GridConstraints.FILL_BOTH,
                        GridConstraints.SIZEPOLICY_FIXED,
                        GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
                        new Dimension(JsonToolWidth, -1), new Dimension(JsonToolWidth, -1), new Dimension(JsonToolWidth, -1)));

    }


    @NotNull
    private Font getEffectiveFont() {
        int size = 14;
        return new Font("Monospaced", Font.PLAIN, size);
    }

    class JwtTextListener implements DocumentListener {


        @Override
        public void insertUpdate(DocumentEvent e) {
            parseJWT();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            parseJWT();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {

        }

        private void parseJWT() {
            try {
                String text = leftTextPane.getText();
                String[] split = text.split("\\.");
                String s1 = split[1];
                Base64.Decoder decoder = Base64.getDecoder();
                byte[] decode1 = decoder.decode(s1);
                String payLoad = new String(decode1);
                JsonUtils.toBean(payLoad, Object.class);

                responseTree.setRootVisible(true);
                VTreeShow vTreeShow = new VTreeShow(responseTree, FONT);
                vTreeShow.showInTree(payLoad);
                responseTree.addMouseListener(new VTreeMouseListener(responseTree,vTreeShow.getJsonEleTreeMap()));
            } catch (JsonException jsonException) {
                DefaultTreeModel model = (DefaultTreeModel) responseTree.getModel();
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
                root.removeAllChildren();
                model.reload(root);
            } catch (Exception e) {
                DefaultTreeModel model = (DefaultTreeModel) responseTree.getModel();
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
                root.removeAllChildren();
                model.reload(root);
            }
        }
    }



}